//
//  UserAccount.swift
//  lixiangweibo
//
//  Created by dyy on 15/11/28.
//  Copyright © 2015年 lixianggongzuoshi. All rights reserved.
//

import UIKit

class UserAccount: NSObject,NSCoding {
    //字典转模型
    var access_token: String?
    var expires_in: NSTimeInterval = 0{
    
        didSet{
            
        expires_date = NSDate(timeIntervalSinceNow: expires_in)
        
        }
    
    }
    var expires_date: NSDate?
    var uid: String?
    var name: String?
    var avatar_large: String?
    
  init(dict: [String: AnyObject]) {
        
        super.init()
        
        setValuesForKeysWithDictionary(dict)
        
    }

    override func setValue(value: AnyObject?,  forUndefinedKey key: String) {
        
    }
    //过滤
    override var description: String{
        
        let keys = ["access_token","expires_date","uid","name","avatar_large"]
        let dict = dictionaryWithValuesForKeys(keys)
        return dict.description
    }
    
    //归档
    func encodeWithCoder(aCoder: NSCoder) {
        
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(expires_date, forKey: "expires_date")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")

        
    }
    //返归档
    required init (coder aDecoder: NSCoder) {
     
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_date = aDecoder.decodeObjectForKey("expires_date") as? NSDate
        uid  = aDecoder.decodeObjectForKey("uid") as? String
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }
    //保存
    
    func saveAccount(){
    let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString) .stringByAppendingPathComponent("234.plist")
        NSKeyedArchiver.archiveRootObject(self, toFile: path)
    
    }
    //读取 要用类方法
    
 class   func loadAccount() -> UserAccount?{
    let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString) .stringByAppendingPathComponent("234.plist")
        if  let account = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? UserAccount {
        //OrderedDescending 降序
            if account.expires_date?.compare(NSDate()) == NSComparisonResult.OrderedDescending{
                        return account
            
            }
        

        }
        return nil
    }
    
    
}